<template>
  <c-back-wrap :loading="loading" go-page="经销商门店新建管理" current-page="审核">
    <QupFormContainer :column="1">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="110px">
        <el-form-item prop="fileReviewResult" label="审批结果">
          <c-dict-select v-model="formData.fileReviewResult" dict-type-code="REVIEW_RESULT" clearable placeholder="审批结果" />
        </el-form-item>
        <el-form-item v-if="[2, '2'].includes(formData.fileReviewResult)" prop="assistToHandleAccount" label="协办用户" :span="24/4">
          <c-common-search-qup-person v-model="formData.assistToHandleAccount" :label.sync="formData.assistToHandleName" multiple placeholder="协办用户" />
        </el-form-item>
        <el-form-item prop="fileReviewAdvice" label="审批意见" :span="24">
          <el-input v-model="formData.fileReviewAdvice" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 3}" placeholder="审批意见" clearable />
        </el-form-item>
      </el-form>
    </QupFormContainer>

    <c-title v-if="editable" title="经销商-客户业务类型变更信息">
      <CustomerBusinessTypeChange ref="customerBusinessTypeChange" v-model="businessTypeFormData" :detail="detail" :start-observe="startObserve" />

    </c-title>

    <c-title title="经销商-客户基本信息">
      <CustomerBaseInfoView :detail="detail" />
    </c-title>

    <c-title title="经销商-门店基本信息">
      <QupList :column="3" sep="：" default-value="" label-position="right" label-width="150">
        <QupListItem v-if="editable" key="code" :value="detail.code" label-width="0" :span="24">
          <el-form ref="formShop" :model="shopFormData" :rules="formRules" label-width="130px">
            <el-form-item label="门店编码" prop="code">
              <c-common-search-shop-by-customer
                v-model="shopFormData.code"
                :label.sync="shopFormData.name"
                :format-label="v=>v.code"
                :customer-code="detail.customerCode"
                :disabled="!detail.customerCode"
                :depend-on-observe="detail.customerCode"
                start-observe
                style="width:240px"
                @change="handleShopChange"
              />
            </el-form-item>
            <!-- <el-form-item label="门店编码" prop="name">
              <span>{{ shopFormData.name }}</span>
            </el-form-item> -->
          </el-form>
        </QupListItem>
        <QupListItem key="name" label="门店名称" :value="changeShopFormData.name" />
        <QupListItem key="businessTypeName" label="门店经营业务类型" :value="changeShopFormData.businessTypeName" />
        <QupListItem key="shopClassifyName" label="门店类型" :value="changeShopFormData.shopClassifyName" />
        <QupListItem key="countryName" label="国别" :value="changeShopFormData.countryName" />
        <QupListItem key="provinceName" label="省份" :value="changeShopFormData.provinceName" />
        <QupListItem key="cityName" label="城市" :value="changeShopFormData.cityName" />
        <QupListItem key="countyName" label="区/县" :value="changeShopFormData.countyName" />
        <QupListItem key="townName" label="街道/乡镇" :value="changeShopFormData.townName" />
        <QupListItem key="shopAddr" label="详细地址" :value="changeShopFormData.shopAddr" :span="24" />
        <QupListItem key="floor" label="所在楼层" :value="changeShopFormData.floor" />
        <QupListItem key="cityLevelName" label="城市级别" :value="changeShopFormData.cityLevelName" />
        <QupListItem key="marketLevelName" label="市场层级" :value="changeShopFormData.marketLevelName" />
        <QupListItem key="shopInfoPhone" label="门店咨询电话" :value="changeShopFormData.shopInfoPhone" />
        <QupListItem key="shopServPhone" label="售后电话" :value="changeShopFormData.shopServPhone" />
        <QupListItem key="outpicArea" label="出图总面积(㎡)" :value="changeShopFormData.outpicArea || 0" />
        <QupListItem key="isDecorationDoorHead" label="是否装修门头" :value="changeShopFormData.isDecorationDoorHead" dict-type-code="BOOLEANS" :prop-enum="{domainCode:'marketing',appCode:'slm'}" />
        <!-- <QupListItem key="doorHeadArea" label="门头面积(㎡)" :value="changeShopFormData.doorHeadArea || 0" /> -->
        <QupListItem key="isDeposit" label="是否缴纳保证金" :value="detail.isDeposit" dict-type-code="BOOLEANS" :prop-enum="{domainCode:'marketing',appCode:'slm'}" />
        <QupListItem v-if="[1, '1'].includes(detail.isDeposit)" key="depositDate" label="保证金缴纳日期" :value="$trimHMS(detail.depositDate)" />
        <QupListItem key="finishedDeposit" label="成品保证金金额(元)" :value="`${detail.finishedDeposit || 0}`" />
        <QupListItem key="customizedDeposit" label="定制保证金金额(元)" :value="`${detail.customizedDeposit || 0}`" />
        <QupListItem key="cupboardDeposit" label="橱柜保证金金额(元)" :value="`${detail.cupboardDeposit || 0}`" />
        <QupListItem key="bathroomDeposit" label="卫浴保证金金额(元)" :value="`${detail.bathroomDeposit || 0}`" />
        <QupListItem label="营业执照图片" :span="24">
          <c-file-list v-model="shopFormData.ACCESS060" :uploadable="editable" :editable="editable" direct-del :model-id="shopDTO.id" view-type="list" type-code="ACCESS060" />
          <!-- <c-file-list :uploadable="false" :editable="false" :model-id="shopDTO.id" view-type="list" type-code="ACCESS055" /> -->
        </QupListItem>
        <QupListItem label="专卖店特许经营合同图片" :span="24">
          <c-file-list v-model="shopFormData.ACCESS061" :uploadable="editable" :editable="editable" direct-del :model-id="shopDTO.id" view-type="list" type-code="ACCESS061" />
          <!-- <c-file-list :uploadable="false" :editable="false" :model-id="shopDTO.id" view-type="list" type-code="ACCESS056" /> -->
        </QupListItem>
        <QupListItem key="endProductArea" label="成品面积(㎡)" :value="shopDTO.endProductArea || 0" />
        <QupListItem key="fullHouseArea" label="全屋定制面积(㎡)" :value="shopDTO.fullHouseArea || 0" />
        <QupListItem key="cabinetArea" label="整体橱柜面积(㎡)" :value="shopDTO.cabinetArea || 0" />
        <QupListItem key="bathroomArea" label="卫浴面积(㎡)" :value="shopDTO.bathroomArea || 0" />
        <QupListItem key="modelRoomArea" label="样板间面积(㎡)" :value="shopDTO.modelRoomArea || 0" />
        <QupListItem key="curtainArea" label="窗帘面积(㎡)" :value="shopDTO.curtainArea || 0" />
        <QupListItem key="cabinetSuite" label="橱柜套数" :value="shopDTO.cabinetSuite" />
        <QupListItem key="bathroomSuite" label="卫浴套数" :value="shopDTO.bathroomSuite" />
        <QupListItem key="totalArea" label="单店总面积(㎡)" :value="shopDTO.totalArea || 0" />
        <QupListItem key="headTypeName" label="门头类型" :value="shopDTO.headTypeName" />
        <QupListItem key="doorHeadArea" label="门头面积(㎡)" :value="shopDTO.doorHeadArea || 0" />
        <QupListItem key="lintelArea" label="门楣面积(㎡)" :value="shopDTO.lintelArea || 0" />
      </QupList>
    </c-title>
    <c-title title="经销商-门店联系人信息">
      <ContactsTable title="经销商-门店联系人信息" :table-data="shopContactsData" type="view" />
    </c-title>
    <c-title title="经销商-门店报图信息">
      <QupList :column="3" sep="：" default-value="" label-position="right" label-width="130">
        <QupListItem key="isReportPic" label="是否报图" :value="shopDTO.isReportPic" :span="24" dict-type-code="BOOLEANS" :prop-enum="{domainCode:'marketing',appCode:'slm'}" />
        <QupListItem v-if="shopDTO && shopDTO.id" label="特殊建档附件" :span="24">
          <c-file-list v-model="shopFormData.ACCESS062" :uploadable="editable" :editable="editable" direct-del tip="如未报图/未交保证金等情况，业务请示申请审核通过的流程附件" :model-id="shopDTO.id" view-type="list" type-code="ACCESS062" />
          <!-- <c-file-list :uploadable="false" :editable="false" :model-id="shopDTO.id" view-type="list" type-code="ACCESS062" /> -->
        </QupListItem>
      </QupList>
    </c-title>
    <c-title title="经销商-门店收货地址信息">
      <div class="el-form-item el-form-item--mini">
        <span class="el-form-item__label">原收货地址信息</span>
      </div>
      <AddrTable ref="oldAddrTable" title="原收货地址信息" :table-data="oldAddrTableData" type="view" />
      <div class="el-form-item el-form-item--mini" style="padding-top: 10px;display:flex;align-items:center;">
        <span class="el-form-item__label">新增收货地址</span>
      </div>
      <AddrTable
        ref="newAddrTable"
        title="新增收货地址"
        :table-data="newAddrTableData"
        type="view"
        :show-edit-addr-code="editable"
        :start-observe="startObserve"
        :customer-code="detail.customerCode"
      />
    </c-title>
    <c-title title="经销商-门店交接信息">
      <QupList :column="3" sep="：" default-value="" label-position="right" label-width="120">
        <QupListItem key="isMarketConnect" label="是否属于交接门店" :value="detail.isMarketConnect" :span="24" dict-type-code="BOOLEANS" :prop-enum="{domainCode:'marketing',appCode:'slm'}" />
        <template v-if="[1,'1'].includes(detail.isMarketConnect)">
          <QupListItem label-width="0" :span="24">
            <DistributionTable ref="distributionTable" filter-q-y-q-j-k-u title="经销商-门店交接信息" :office-code="detail.officeCode" :customer-code="detail.customerCode" :table-data="distributionTableData" :type="editable?'edit':'view'" />
            <!-- <DistributionTable ref="distributionTable" title="经销商-门店交接信息" :office-code="detail.officeCode" :customer-code="detail.customerCode" :editable-column="['toAccountCode']" :table-data="distributionTableData" type="view" /> -->
          </QupListItem>
          <QupListItem label="经销商交接证明" :span="24">
            <c-file-list v-if="finishedDetail" v-model="formData.ACCESS063" :uploadable="editable" :editable="editable" direct-del :model-id="id" view-type="list" type-code="ACCESS063" />
            <!-- <c-file-list :uploadable="false" :editable="false" v-if="finishedDetail" :model-id="id" view-type="list" type-code="ACCESS063" /> -->
          </QupListItem>
          <QupListItem label="经销商关系证明" :span="24">
            <c-file-list v-if="finishedDetail" v-model="formData.ACCESS064" :uploadable="editable" :editable="editable" direct-del :model-id="id" view-type="list" type-code="ACCESS064" />
            <!-- <c-file-list :uploadable="false" :editable="false" v-if="finishedDetail" :model-id="id" view-type="list" type-code="ACCESS064" /> -->
          </QupListItem>
          <QupListItem label="交接双方现场签订照片" label-width="160px" :span="24">
            <c-file-list v-if="finishedDetail" v-model="formData.ACCESS111" :uploadable="editable" :editable="editable" direct-del :model-id="id" view-type="list" type-code="ACCESS111" />
          </QupListItem>
          <QupListItem v-if="finishedDetail" prop="1" label="交接双方现场签订照片模板下载" label-width="190px" :span="24">
            <div class="template-down" @click.stop="handleDownTemplate(ACCESS111.id)">
              <span>交接双方现场签订照片模板下载</span>
              <i class="el-icon-download" />
            </div>
          </QupListItem>
        </template>
      </QupList>
    </c-title>
    <c-title title="BPM审核信息">
      <QupList :column="3" sep="：" default-value="" label-position="right" label-width="150">
        <QupListItem :value="detail.createBy" label="申请人" />
        <QupListItem :value="detail.createTime" label="申请时间" />
        <QupListItem :value="detail.applyNo" label="BPM单号" />
        <QupListItem label="客户经理门店新建提报原始表单" label-width="200px" :span="24">
          <c-file-list :uploadable="false" :editable="false" view-type="list" type-code="ACCESS081" />
        </QupListItem>
        <!-- <QupListItem key="officeReviewResult" label="办事处审批结果" :value="detail.officeReviewResult" dict-type-code="REVIEW_RESULT" :prop-enum="{domainCode:'marketing',appCode:'slm'}" /> -->
        <!-- <QupListItem :value="detail.officeReviewTime" label="办事处审批结束时间" /> -->
        <!-- <QupListItem :value="detail.officeReviewAdvice" label="办事处审批意见" :span="24" /> -->
        <!-- <QupListItem :value="detail.officeAccountingReviewAdvice" label="办事处会计处理意见" :span="24" /> -->
      </QupList>
      <Options :data="detail.opinionDTOS" />
    </c-title>

    <div class="btn-center">
      <c-button type="default" @click="handleCancel">取消</c-button>
      <c-button type="primary" @click="handleConfirm">确认</c-button>
    </div>
  </c-back-wrap>
</template>
<script>
import { shopDetail, shopAduit } from '@/api/channelTask2/newShop'
import AddrTable from '../../components/AddrTable'
import ContactsTable from '../../components/ContactsTable'
import DistributionTable from '../../components/DistributionTable'
import CustomerBaseInfoView from '../../components/CustomerBaseInfoView'
import CustomerBusinessTypeChange from '../../components/CustomerBusinessTypeChange'
import Options from '../../components/Options'
import { contactByShop, downTemplate, getTemplateConfig } from '@/api/channelTask2/change'

export default {
  name: 'Audit',
  components: {
    AddrTable,
    ContactsTable,
    DistributionTable,
    CustomerBaseInfoView,
    CustomerBusinessTypeChange,
    Options
  },
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      detail: {},
      loading: false,
      formData: {
        fileReviewResult: '',
        fileReviewAdvice: '',
        assistToHandleAccount: [],
        assistToHandleName: [],
        // 交接附件
        ACCESS063: [],
        ACCESS064: [],
        ACCESS111: []
      },
      businessTypeFormData: {},
      shopFormData: {
        businessType: '',
        businessTypeName: '',
        code: '',
        name: '',
        shopClassify: '',
        shopClassifyName: '',
        countryCode: '', //	国家
        countryName: '',
        province: '', //	省份
        provinceName: '',
        city: '', //	城市
        cityName: '',
        county: '', //	区县
        countyName: '',
        town: '', //	街道
        townName: '',
        shopAddr: '',
        floor: '',
        cityLevel: '', //	城市级别
        cityLevelName: '',
        marketLevelCode: '', //	市场层级
        marketLevelName: '',
        shopInfoPhone: '',
        shopServPhone: '',
        outpicArea: '',
        isDecorationDoorHead: '',
        doorHeadArea: '',
        // 附件
        ACCESS060: [],
        ACCESS061: [],
        ACCESS062: []
      },
      oldAddrTableData: [],
      newAddrTableData: [],
      distributionTableData: [],
      businessTypeData: [],
      startObserve: false,
      // mdm门店联系人
      mdmShopContactsData: [],
      ACCESS111: {}
    }
  },
  computed: {
    isEdit() {
      return !!this.id
    },
    editable() {
      return [1, '1'].includes(this.formData.fileReviewResult)
    },
    changeShopFormData() {
      return this.editable && !!this.shopFormData.code ? this.shopFormData : this.shopDTO
    },
    shopDTO() {
      return this.detail.shopDTO || {}
    },
    formRules() {
      return {
        fileReviewResult: [{ required: true, message: '请选择审批结果', trigger: 'change' }],
        assistToHandleAccount: [{ required: true, validator: (r, v, c) => {
          if (!v || v.length === 0) {
            c(new Error('请选择协办用户'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        fileReviewAdvice: [{ required: true, message: '请输入审批意见', trigger: 'change' }],
        code: [{ required: this.editable, message: '请选择门店', trigger: 'change' }]
      }
    },
    hasIsTransferSales() {
      return this.distributionTableData.some(e => [1, '1'].includes(e.isTransferSales))
    },
    finishedDetail() {
      return this.detail && Object.keys(this.detail).length > 0
    },
    // 门店联系人
    shopContactsData() {
      return this.editable ? this.mdmShopContactsData : (this.detail.contactDTOS || [])
    }
  },
  created() {
    this.getDetailData().then(res => {
      setTimeout(() => {
        this.startObserve = true
      }, 200)
    })
    this.templateConfig()
  },
  methods: {
    getDetailData() {
      this.loading = true
      return shopDetail(this.id).then(res => {
        this.detail = res.data
        this.loading = false
        this.initFormData()
      }).catch(() => {
        this.loading = false
      })
    },
    handleCancel() {
      this.$pageStack.pop()
    },
    initFormData() {
      this.oldAddrTableData = (this.detail.addressDTOS || []).filter(e => [1, '1'].includes(e.isBefore))
      this.newAddrTableData = (this.detail.addressDTOS || []).filter(e => ![1, '1'].includes(e.isBefore))
      // 交接信息
      this.distributionTableData = this.detail.handoverDTOS || []
    },
    async validate() {
      await this.$refs.form.validate()
      if (this.editable) {
        await this.$refs.customerBusinessTypeChange.validate()
        await this.$refs.formShop.validate()

        // 校验附件
        const validator = (v, msg) => {
          if (!v || !(v instanceof Array) || v.length === 0) {
            return msg
          }
          return false
        }
        const fileRules = {
          ACCESS060: '请上传营业执照图片',
          ACCESS061: '请上传专卖店特许经营合同图片',
          ACCESS063: '请上传经销商交接证明',
          ACCESS064: '请上传经销商关系证明',
          ACCESS111: '请上传交接双方现场签订照片'
        }
        const errMsg = []

        'ACCESS060 ACCESS061'.split(' ').forEach(
          k => {
            const msg = fileRules[k]
            if (!msg) return
            const v = this.shopFormData[k]
            const result = validator(v, msg)
            result && errMsg.push(result)
          }
        )
        // 交接附件
        if ([1, '1'].includes(this.detail.isMarketConnect)) {
          'ACCESS063 ACCESS064 ACCESS111'.split(' ').forEach(
            k => {
              const msg = fileRules[k]
              if (!msg) return
              if ('ACCESS064'.includes(k) && !this.hasIsTransferSales) {
                return
              }
              const v = this.formData[k]
              const result = validator(v, msg)
              result && errMsg.push(result)
            }
          )
        }
        // 交接信息
        if ([1, '1'].includes(this.detail.isMarketConnect) && this.distributionTableData.length === 0) {
          errMsg.push('【经销商-门店交接信息】至少有一条数据!')
        }

        if (errMsg.length > 0) {
          this.$message({
            type: 'warning',
            dangerouslyUseHTMLString: true,
            message: `<div>${errMsg.join('<br>')}</div>`
          })
          return Promise.reject(false)
        }
        // 交接信息
        if ([1, '1'].includes(this.detail.isMarketConnect)) {
          await this.$refs.distributionTable.validate()
        }

        for (let i = 0; i < this.newAddrTableData.length; i++) {
          const t = this.newAddrTableData[i]
          if (!t.code) {
            this.$message.warning(`请选择【经销商-门店收货地址信息】【新增收货地址信息】第${i + 1}行地址编码!`)
            return Promise.reject(false)
          }
        }
        for (let i = 0; i < this.distributionTableData.length; i++) {
          const t = this.distributionTableData[i]
          if (!t.toAccountCode) {
            this.$message.warning(`请选择【经销商-门店交接信息】第${i + 1}行现业务账号编码!`)
            return Promise.reject(false)
          }
        }
      }
      return Promise.resolve(true)
    },
    getPostData() {
      // 门店附件
      const sfd = this.$deepClone(this.shopFormData)
      const fd = this.$deepClone(this.formData)
      if (this.editable) {
        sfd.attachmentDTOS = [
          ...this.$getFiles(sfd.ACCESS060 || []),
          ...this.$getFiles(sfd.ACCESS061 || []),
          ...this.$getFiles(sfd.ACCESS062 || [])
        ]
        // 交接附件
        fd.attachmentDTOS = [
          ...this.$getFiles(fd.ACCESS063 || []),
          ...this.$getFiles(fd.ACCESS064 || []),
          ...this.$getFiles(fd.ACCESS111 || [])
        ]
      }
      'ACCESS060 ACCESS061 ACCESS062'.split(' ').forEach(k => {
        delete sfd[k]
      })
      'ACCESS063 ACCESS064 ACCESS111'.split(' ').forEach(k => {
        delete fd[k]
      })

      const data = {
        ...fd,
        ...this.businessTypeFormData,
        id: this.id,
        addressDTOS: [
          ...this.$deepClone(this.oldAddrTableData),
          ...this.$deepClone(this.newAddrTableData)
        ].map(e => {
          const t = { ...e }
          const reg = /^_.+/
          Object.keys(t).forEach(k => {
            if (reg.test(k)) {
              delete t[k]
            }
          })
          return t
        }),
        handoverDTOS: this.distributionTableData,
        shopDTO: {
          ...this.shopDTO,
          ...sfd
        }
      }
      data.afterBusinessTypeCode = (data.afterBusinessTypeCode || []).join(',')
      data.afterBusinessTypeName = (data.afterBusinessTypeName || []).join(',')
      // 处理协办用户
      if (data.assistToHandleAccount instanceof Array) {
        data.assistToHandleAccount = data.assistToHandleAccount.join('，')
        data.assistToHandleName = data.assistToHandleName.join('，')
      }
      return data
    },
    handleConfirm() {
      return this.validate().then(() => {
        return shopAduit(this.getPostData()).then(res => {
          this.$message.success('操作成功!')
          this.$pageStack.pop('onPage')
        })
      })
    },
    handleShopChange(value) {
      if (!value) {
        value = {}
      }
      Object.entries(this.shopFormData).forEach(([k, v]) => {
        if (/^ACCESS/.test(k)) {
          return
        }
        this.$set(this.shopFormData, k, value[k] !== undefined ? value[k] : v)
      })
      if (value.code) {
        contactByShop(value.code).then(res => {
          this.mdmShopContactsData = res.data
        })
      } else {
        this.mdmShopContactsData = []
      }
    },
    handleDownTemplate(id) {
      downTemplate(id)
    },
    templateConfig() {
      getTemplateConfig('ACCESS111').then(res => {
        this.ACCESS111 = res
      })
    }
  }
}
</script>
